﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SimpleRest.Core.Routing;
using SimpleRest.Core;
using SimpleRest.WebTest.Entities;

namespace SimpleRest.WebTest.Handlers
{
    /// <summary>
    /// Determine if a querystring of key=filter exists.  If it does then expect format of value to be {a, b, c, ...} and return a filter object
    /// containing the values within the comma delim. list.  If not return null.
    /// </summary>
    public class FilterMappingHandler : OperationMappingHandler
    {
        public FilterMappingHandler()
            : base("filter") { }
        public FilterMappingHandler(string outputParameterName)
            : base(outputParameterName) { }

        public override object ExecuteMapping(IHttpRequestMessage request, Operation operation)
        {
            var uriSplit = request.Uri.Split(new char[] { '?' });
            string querystring = null;

            if (uriSplit.Length > 1)
            {
                querystring = uriSplit[1];
                foreach (var str in querystring.Split(new char[] { '&' }))
                {
                    var split = str.Split(new char[] { '=' });
                    string key = null;
                    string value = null;

                    if (split.Length > 0)
                        key = split[0];
                    if (split.Length > 1)
                        value = split[1];

                    if (key.ToLower().Equals("filter"))
                    {
                        if (value.StartsWith("{") && value.EndsWith("}"))
                        {
                            List<string> items = new List<string>();
                            foreach (var item in value.Trim(new char[] { '}', '{' }).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                items.Add(item.Trim());
                            }
                            return new Filter(items);
                        }
                    }
                }
            }
            
            return null;
        }
    }
}